package com.lewis.anf;

import java.io.BufferedInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.List;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;

import com.lewis.anf.pojo.AnfBaseItem;
import com.lewis.anf.pojo.AnfCat;
import com.lewis.anf.pojo.AnfCategory;
import com.lewis.anf.pojo.AnfUrlsPair;
import com.lewis.anf.servlet.InitWebSocketServlet;
import com.lewis.anf.websocket.AnfWebSocket;

public class AnfDownloadThread extends Thread {

	private static List<String> size;
	
	private AnfCat cats;
	
	public AnfDownloadThread(AnfCat cats){
		List<String> ss = new ArrayList<String>();
		ss.add("00");
		ss.add("0");
		ss.add("2");
		ss.add("XS");
		ss.add("S");
		this.size = ss;
		this.cats = cats;
	}
	
	@Override
	public void run() {
		
		System.getProperties().setProperty("webdriver.chrome.driver", "/Users/henrylian/Downloads/chromedriver");
        WebDriver webDriver = new ChromeDriver();
        
		for(AnfCategory anfC:cats.getList()){
			for(AnfBaseItem anfB:anfC.getItems()){
				for(AnfUrlsPair anfU:anfB.getUrls()){
			        webDriver.get(anfU.getItemUrl());
			        WebElement webElement = webDriver.findElement(By.xpath("/html"));
					
					Document doc = Jsoup.parse(webElement.getAttribute("outerHTML"));
					
					//check the size
					Element size = doc.getElementsByClass("size").get(0);
					Elements option = size.select("select > option");
					List<String> availableList = new ArrayList<String>();
					for (Element o:option){
						String s = o.toString();
						s = s.replaceAll("[\n\r\t]","");
						String b = s.substring(s.indexOf(">")+1);
						String c = b.substring(0, b.indexOf("<"));
						System.out.println("value is: "+c);
						
						if(getSize().contains(c)){
							availableList.add(c);
						}
					}
					if (availableList.isEmpty()){
						String msg = "{\"id\":\"" + anfB.getProdId() + "\", \"msg\":" + "\"no size available\"}";
						sendMessage(msg);
					} else{
						//download
						//analyze urls and put in the list
						List<AnfUrlsPair> urlList = new ArrayList<AnfUrlsPair>();
						Element thumbnails = doc.getElementsByClass("thumbnails").get(0);
						Elements lis = thumbnails.getElementsByTag("li");
						for(Element e:lis){
							if (e.attr("data-image-type").equals("product")){
								String url = "http:" + e.getElementsByTag("img").get(0).attr("src").toString();
								AnfUrlsPair aup = new AnfUrlsPair();
								aup.setItemUrl(url);
								aup.setPicUrl("thumbnail");
								urlList.add(aup);
								url = url.replaceAll("anfThumbnail", "anfProductImage500");
								AnfUrlsPair aup1 = new AnfUrlsPair();
								aup1.setItemUrl(url);
								aup1.setPicUrl("image500");
								urlList.add(aup1);
								url= url.replaceAll("anfProductImage500", "anfProductImageMagnify");
								AnfUrlsPair aup2 = new AnfUrlsPair();
								aup2.setItemUrl(url);
								aup2.setPicUrl("imageMagnify");
								urlList.add(aup2);
							} else if (e.attr("data-image-type").equals("model")){
								String url = "http:" + e.getElementsByTag("img").get(0).attr("src").toString();
								AnfUrlsPair aup = new AnfUrlsPair();
								aup.setItemUrl(url);
								aup.setPicUrl("thumbnail");
								urlList.add(aup);
								url = url.replaceAll("anfPDPModBottomThumbnail", "anfProductImageModBottom500");
								AnfUrlsPair aup1 = new AnfUrlsPair();
								aup1.setItemUrl(url);
								aup1.setPicUrl("image500");
								urlList.add(aup1);
								url= url.replaceAll("anfProductImageModBottom500", "anfProductImageModBottomMagnify");
								AnfUrlsPair aup2 = new AnfUrlsPair();
								aup2.setItemUrl(url);
								aup2.setPicUrl("imageMagnify");
								urlList.add(aup2);
							} else{
								String id = doc.getElementsByClass("image-wrap").get(0).attr("id");
								AnfUrlsPair aup = new AnfUrlsPair();
								aup.setItemUrl("http://anf.scene7.com/is/image/anf/anf_" + id + "_360?$product360pdp500$");
								aup.setPicUrl("360view");
								urlList.add(aup);
							}
						}
						
						for (AnfUrlsPair aup:urlList){
							URL uri;
							String url = aup.getItemUrl();
							url.lastIndexOf("/");
							String name = url.substring(url.lastIndexOf("/")+1, url.indexOf("?"));
							try {
								uri = new URL(url);
								InputStream in = new BufferedInputStream(uri.openStream());
								String mimeType = URLConnection.guessContentTypeFromStream(in);
								ByteArrayOutputStream out = new ByteArrayOutputStream();
								byte[] buf = new byte[1024];
								int n = 0;
								while (-1!=(n=in.read(buf)))
								{
								   out.write(buf, 0, n);
								}
								out.close();
								in.close();
								byte[] response = out.toByteArray();
								String folderpath = "/Users/henrylian/Desktop/anf/"+anfC.getName()+"/" + anfB.getProdId();
								String fileName = name+"_"+aup.getPicUrl()+"."+mimeType.substring(mimeType.indexOf("/")+1);
								File  dirFile = new File(folderpath);
								boolean bFile   = dirFile.exists();
					             if( bFile == true )
					             {
					                System.out.println("The folder exists.");
					             }
					             else
					             {
					                System.out.println("The folder do  not exist,now trying to create a one...");
					 
					                bFile = dirFile.mkdirs();
					                if( bFile == true )
					                {
					                   System.out.println("Create successfully!");
					                }
					                else
					                {
					                    System.out.println("Disable to make the folder,please check the disk is full or not.");
					                }
					             }
								FileOutputStream fos = new FileOutputStream(folderpath+ "/"+fileName);
								fos.write(response);
								fos.close();
								System.out.println("downloading url:  "+ uri);
							} catch (Exception e1) {
								// TODO Auto-generated catch block
								e1.printStackTrace();
							}
							
						}
						String msg = "{\"id\":\"" + anfB.getProdId() + "\", \"msg\":" + "\"download completed\"}";
						sendMessage(msg);
					}
					
					
				}
			}
		}
		webDriver.close();
		System.out.println("downloading completed-----------------------------");
	}
	
	private void sendMessage(String message){
		for(AnfWebSocket anfW:InitWebSocketServlet.getSocketList()){
			sendMessage(anfW, message);
		}
	}
	
	private void sendMessage(AnfWebSocket client, String message){
	    try {
	        client.getConnection().sendMessage(message);
	    } catch (IOException e) {
	        e.printStackTrace();
	    }
	}

	public static List<String> getSize() {
		return size;
	}

	public static void setSize(List<String> size) {
		AnfDownloadThread.size = size;
	}

	public AnfCat getCats() {
		return cats;
	}

	public void setCats(AnfCat cats) {
		this.cats = cats;
	}

}
